<?php

namespace App\Http\Controllers\Site\Custom\Provider;

use App\B2BProject\Site\HelperControllerBuildTrait;
use App\B2BProject\Area;
use App\B2BProject\Custom\Business\GoodsCategory;
use App\B2BProject\Custom\Provider\Offer;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Auth;
use Validator;

class OfferController extends Controller
{
    use HelperControllerBuildTrait;

    /**
     * Display a listing of the resource.
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $request->query->set('page', $request->query('page', $request->page));
//        $request->query->set('pageSize', $request->query('pageSize', $request->pageSize));

        $pageSize = $request->query('pageSize', $request->pageSize);
// TODO 应当验证是否为有效用户（否则可能会出现采购商发布供应商的东西）
        if ($request->ajax()) {
            switch ($tab = $request->tab) {
                case -1: // 获取两个 TAB 的数据列表
                    $offers[] = Offer::where('member_id', Auth::id())->available()->orderBy('created_at',
                        'desc')->paginate($pageSize);
                    $offers[] = Offer::where('member_id', Auth::id())->unavailable()->orderBy('created_at',
                        'desc')->paginate($pageSize);

                    $data = [];

                    for ($i = 0; $i <= 1; $i++) {
                        foreach ($offers[$i] as $offer) {
                            $data[$i]['detail'][] = [
                                'id'          => $offer->id,
                                'goodsname'   => $offer->title,
                                'price'       => $offer->price,
                                'amount'      => $offer->amount,
                                'unit'        => $offer->unit,
                                'orderamount' => $offer->minimum_order,
                                'pubdate'     => date('Y-m-d', strtotime($offer->created_at)),
                                'district'    => Area::getName($offer->province_id) .
                                                 ' ' .
                                                 Area::getName($offer->city_id),
                                'remove'      => $offer->status,
                                'href'        => route('account.offer.edit', $offer->id),
                            ];
                        }

                        $data[$i]['pagingConfData'] = [
                            'page'     => $offers[$i]->currentPage(),
                            'pageSize' => $pageSize,
                            'total'    => $offers[$i]->total(),
                        ];
                    }

                    return response()->json(['data' => $data]);
                    break;
                case 0:
                case 1:
                    $tab    = $tab ^ 1;
                    $offers = Offer::where('member_id', Auth::id())->whereStatus($tab)->orderBy('created_at',
                        'desc')->paginate($pageSize);
                    $data   = [];
                    foreach ($offers as $offer) {
                        $data[] = [
                            'id'          => $offer->id,
                            'goodsname'   => $offer->title,
                            'price'       => $offer->price,
                            'amount'      => $offer->amount,
                            'unit'        => $offer->unit,
                            'orderamount' => $offer->minimum_order,
                            'pubdate'     => date('Y-m-d', strtotime($offer->created_at)),
                            'district'    => Area::getName($offer->province_id) . ' ' . Area::getName($offer->city_id),
                            'remove'      => $offer->status,
                            'href'        => route('account.offer.edit', $offer->id),
                        ];
                    }

                    return response()->json([
                        'data' => [
                            'detail'         => $data,
                            'pagingConfData' => [
                                'page'     => $offers->currentPage(),
                                'pageSize' => $pageSize,
                                'total'    => $offers->total(),
                            ],
                        ],
                    ]);
                    break;
            }
        }

        return view('host/custom/provider/offer/index');
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('host/custom/provider/offer/create')->with('categories', GoodsCategory::getGlobalCategory());
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     *
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $validator = Validator::make(
            $request->except(['_token']),
            [
                'title'                 => 'required',
                'primary_category_id'   => 'required',
                'secondary_category_id' => 'required',
                'price'                 => 'required|numeric',
                'unit'                  => 'required',
                'amount'                => 'required',
                'minimum_order'         => 'required',
                'province_id'           => 'required',
                'city_id'               => 'required',
                'county_id'             => 'required',
            ]
        );

        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator);
        }

        $data = $request->only([
            'title',
            'price',
            'unit',
            'amount',
            'minimum_order',
            'province_id',
            'city_id',
            'county_id',
        ]);// 只取这些数据

        try {
            \DB::transaction(function () use ($request, $data) {
                $offer = Offer::create($data);
                $primaryCategory
                       = GoodsCategory::GlobalCategory()->whereId($request->primary_category_id)->firstOrFail();
                $primaryCategory->offerInPrimary()->save($offer);

                $secondaryCategory
                    = $primaryCategory->children()->whereId($request->secondary_category_id)->firstOrFail();
                $secondaryCategory->offerInSecondary()->save($offer);

                $member = Auth::user();
                $member->publishes()->save($offer);
            });

            return redirect()->route('account.offer.index');
        } catch (ModelNotFoundException $e) {
            // TODO 响应方式肯定要改
            throw $e;
        } catch (\Exception $e) {
            throw $e;
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int $id
     *
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int $id
     *
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        return view('host/custom/provider/offer/edit')->with('offer', Offer::findOrFail($id));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  int                      $id
     *
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $validator = Validator::make(
            $request->except(['_token']),
            [
                'title'                 => 'required',
                'primary_category_id'   => 'required',
                'secondary_category_id' => 'required',
                'price'                 => 'required|numeric',
                'unit'                  => 'required',
                'amount'                => 'required',
                'minimum_order'         => 'required',
                'province_id'           => 'required',
                'city_id'               => 'required',
                'county_id'             => 'required',
            ]
        );

        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator);
        }

        $data = $request->only([
            'title',
            'price',
            'unit',
            'amount',
            'minimum_order',
            'province_id',
            'city_id',
            'county_id',
        ]);// 只取这些数据

        $offer = Offer::findOrFail($id);
        $offer->update($data);

        $primaryCategory = GoodsCategory::GlobalCategory()->whereId($request->primary_category_id)->firstOrFail();
        $primaryCategory->offerInPrimary()->save($offer);

        $secondaryCategory = $primaryCategory->children()->whereId($request->secondary_category_id)->firstOrFail();
        $secondaryCategory->offerInSecondary()->save($offer);

        $member = Auth::user();
        $member->publishes()->save($offer);

        return redirect()->back();
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int $id
     *
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        Offer::findOrFail($id)->delete();

        return redirect()->back();
    }

    /**
     *  取消报盘操作
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function cancel(Request $request)
    {
        $id = $request->input('id');

        Offer::findOrFail($id)->update(['status' => false]);

        if ($request->ajax()) {
            return $this->index($request);
        }

        return redirect()->back();
    }
}
